package juc.day01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程，一个线程打印1-52，另一个打印字母A-Z，打印顺序为12A34B…5152Z。要求用线程间通信
 */
public class T04 {
    public static void main(String[] args) {
        ShareDataOne4 shareDataOne4 = new ShareDataOne4();
        new Thread(()->{shareDataOne4.printNumber();}).start();
        new Thread(()->{shareDataOne4.printWord();}).start();
    }
}

class ShareDataOne4{
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private int flag = 1; // 1:打印数字 2：打印字母

    public void printNumber(){
        lock.lock();
        try {
            // 判断
            while ( flag != 1){
                condition1.await();
            }
            // 干活
            for(int i=1;i<=52;i++){
                System.out.print(i);
                if(i % 2 == 0){
                    // 通知
                    flag = 2;
                    condition2.signal();
                    condition1.await();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printWord(){
        lock.lock();
        try {
            // 判断
            while ( flag != 2){
                condition2.await();
            }
            // 干活
            for(char w = 'A';w<='Z';w++){
                System.out.print(w);
                // 通知
                flag = 1;
                condition1.signal();
                condition2.await();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
